<script setup lang="ts">
import { Query, PageList } from "@/api/exam/types";
import { getGoryTopList, getCreateAdd, getCreateEdit, getCreateList, getCreateDel } from "@/api/exam/index";
import type { FormInstance } from 'element-plus'

const queryFormRef = ref(ElForm); // 查询表单

const loading = ref(false);
const total = ref(0);

const tableData = ref<PageList[]>([]);

const queryParams = reactive<Query>({
  title: ''
});

/**
 * 查询
 */
function handleQuery() {
  loading.value = true;
  getCreateList(queryParams).then(({ data }) => {
    tableData.value = data;
  })
    .finally(() => {
      loading.value = false;
    });
}


/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

// 弹窗数据
const dialog = reactive({
  title: '新增',
  visible: false
});

// 表单校验
const rules = reactive({
  title: [
    { required: true, message: '请输入题库分类名称', trigger: 'blur' }
  ],
  pid: [
    { required: true, message: '请输入顶级题库分类', trigger: 'blur' }
  ],
})

// 新增提交数据
const formData = reactive({
  id: 0,
  title: '',
  pid: '',
  sort: 0,
});


const selectList = ref<any[]>([]);

// 打开弹窗
const hanldeOpenDialog = (data: any | null = null) => {
  dialog.visible = true;

  if (data) {
    dialog.title = '编辑';
    formData.id = data.id;
    formData.title = data.title;
    formData.pid = data.pid;
    formData.sort = data.sort;
  } else {
    dialog.title = '新增';
    formData.id = 0;
    formData.title = '';
    formData.pid = '';
    formData.sort = 0;
  }

  // 获取顶级分类
  getGoryTopList().then(({ data }) => {
    selectList.value = data;
  })
}

// 关闭弹窗
const closeDialog = () => {
  dialog.visible = false;
}

// 新增分类
const ruleFormRef = ref<FormInstance>();
const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (dialog.title == '新增') {
        let res = await getCreateAdd(formData) as any;
        ElMessage.success(res.msg);

      } else {
        let res = await getCreateEdit(formData) as any;
        ElMessage.success(res.msg);
      }

      resetQuery();
      closeDialog();
    }
  })
}

// 删除
const handleDelete = async (id: number) => {
  await ElMessageBox.confirm("确定要删除吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",

  }).then(async () => {
    let res = await getCreateDel({ id: id }) as any;
    ElMessage.success(res.msg);
    handleQuery();
  }).catch(() => {
    ElMessage({
      type: "info",
      message: "已取消删除",
    });
  });;
}

// 初始化用户列表数据
onMounted(() => {
  handleQuery();
});
</script>


<template>
  <div class="app-container">
    <!-- 查询 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="素材分类名称" prop="title">
          <el-input v-model="queryParams.title" placeholder="输入素材分类名称查询" clearable style="width: 200px"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery"><i-ep-search />搜索</el-button>
          <el-button @click="resetQuery">
            <i-ep-refresh />
            重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between">
          <div>
            <el-button @click="hanldeOpenDialog()" type="success"><i-ep-plus />新增</el-button>
          </div>
        </div>
      </template>
      <el-table :data="tableData" row-key="id" border default-expand-all :tree-props="{
        children: 'child'
      }">
        <el-table-column prop="id" label="编号" sortable />
        <el-table-column prop="title" label="分类名称" sortable />
        <el-table-column prop="sum" label="考试数量" sortable />
        <el-table-column label="操作" fixed="right" align="center" width="280">
          <template #default="scope">
            <el-button type="primary" size="small" @click="hanldeOpenDialog(scope.row)"><i-ep-edit />编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row.id)"><i-ep-delete />删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>


    <!-- 新增修改弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="30%" append-to-body @close="closeDialog">
      <el-form ref="ruleFormRef" :model="formData" :rules="rules" label-width="120px">
        <el-form-item label="专题名称" prop="title">
          <el-input v-model="formData.title" placeholder="请输入素材分类名称" />
        </el-form-item>
        <el-form-item label="顶级分类" prop="pid">
          <el-tree-select value-key="id" placeholder="请输入课程分类" v-model="formData.pid"
            :props="{ children: 'child', label: 'title' }" :data="selectList" check-strictly
            :render-after-expand="false">
          </el-tree-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="formData.sort" placeholder="请输入排序" />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit(ruleFormRef)">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
